<template>
    <div class="tabs-view">
        <el-tabs v-model="activeTab" type="card" @tab-remove="removeTab" @tab-click="tabClick">
            <el-tab-pane v-for="tab in tabs" :key="tab.path" :label="tab.title" :name="tab.path"
                :closable="tab.path !== '/dashboard'" />
        </el-tabs>
    </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()
const tabs = ref([
    { title: '首页', path: '/dashboard' }
])
const activeTab = ref(route.path + '')

function getTitleByPath(path) {
    switch (path) {
        case '/dashboard': return '首页'
        case '/users': return '用户管理'
        case '/role': return '角色管理'
        case '/permission': return '权限管理'
        case '/files': return '文件管理'
        case '/system': return '系统设置'
        case '/logs': return '日志管理'
        case '/help': return '帮助中心'
        case '/profile': return '个人中心'
        default: return '页面'
    }
}

// 保证activeTab和路由始终同步
watch(
    () => route.path,
    (newPath) => {
        activeTab.value = newPath + ''
        if (!tabs.value.find(tab => tab.path === newPath)) {
            tabs.value.push({ title: getTitleByPath(newPath), path: newPath })
        }
    },
    { immediate: true }
)

// 监听tab切换，切换路由
watch(activeTab, (val) => {
    if (val !== route.path) {
        router.push(val)
    }
})

function removeTab(targetName) {
    const idx = tabs.value.findIndex(tab => tab.path === targetName)
    if (idx !== -1) {
        tabs.value.splice(idx, 1)
        // 跳转到上一个标签或首页
        const nextTab = tabs.value[idx - 1] || tabs.value[0]
        router.push(nextTab.path)
    }
}

function tabClick(tab) {
    // 这里可以不用写，v-model和watch已自动切换
}
</script>

<style scoped>
.tabs-view {
    background: #fff;
    border-bottom: 1px solid #f0f0f0;
    padding: 0 16px;
}
</style>